/**
 * 封装数据库的增删改查的SQL方法
 * NOTE: 错误优先回调
 */
module.exports = {
  insert(CollName, insertData) {
    return new Promise((resolve, reject) => {
      CollName.insertMany(insertData, (err, data) => {
        err ? reject(err) : resolve(data)
      })
    })
  },
  find(CollName, whereObj, showObj, sortObj = {}, num = "") {
    /**
     * whereObj: {
     *  $or: [
     *    {name: 'xxx'},
     *    {password: 'xxx'},
     *    {username: /^xxx$/'}
     *    //正则模糊查找: /^xxx/ /^xxx$/ /xxx$/ new RegExp('/^xxx/')
     *  ]
     * }
     * 
     * sortObj: {
     *  year: -1// -1是降序
     * }
     * */
    return new Promise((resolve, reject) => {
      CollName.find(whereObj, showObj).sort(sortObj).limit(num).exec((err, data) => {
        err ? reject(err) : resolve(data)
      })
    })
  },
  delete(CollName, deleteObj) {
    return new Promise((resolve, reject) => {
      CollName.deleteMany(deleteObj).exec((err, data) => {
        err ? reject(err) : resolve(data)
      })
    })
  },
  modify(CollName, query, update) {
    /*
    update: {
      $set: {tel: 000, ...},
      $inc: { age: 16 } 减则加上复数
    }
    */
    return new Promise((resolve, reject) => {
      CollName.updateMany(query, update).exec((err, data) => {
        err ? reject(err) : resolve(data)
      })
    })
  }
}